package image.disk;

import image.Image3;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import math.vec2i;
import math.vec3;

public class FormatPNG
{
    
    private FormatPNG()
    {
    }
    
    
    public static Image3 load(String aFullPath)
    {
        if (!aFullPath.endsWith(".png"))
        {
            aFullPath += ".png";
        }
        File file = new File(aFullPath);
        BufferedImage loadImg = null;
        try
        {
            loadImg = ImageIO.read(file);
        }
        catch (Exception e)
        {
            System.err.println("Failed to read image from disk!");
        }
        vec2i size = new vec2i(loadImg.getWidth(), loadImg.getHeight());
        Image3 image = new Image3(size);
        vec2i ind = new vec2i();
        for (ind.y = 0; ind.y < size.y; ind.y++)
        {
            for (ind.x = 0; ind.x < size.x; ind.x++)
            {
                // Grab pixel data from the image:
                int argb = loadImg.getRGB(ind.x, ind.y);
                // Unpack pixel data from ARGB format:
                int a = (argb >> 24) & 0xFF;
                int r = (argb >> 16) & 0xFF;
                int g = (argb >> 8) & 0xFF;
                int b = argb & 0xFF;
                // Convert to floating-point:
                vec3 datum = new vec3(r, g, b);
                datum.div(255.0);
                // Copy floating-point datum to result:
                image.write(ind, datum);
            }
        }
        return image;
    }
    
    public static void save(Image3 aImage, String aFullPath)
    {
        if (!aFullPath.endsWith(".png"))
        {
            aFullPath += ".png";
        }
        BufferedImage img = new BufferedImage(
            aImage.mSize.x, 
            aImage.mSize.y, 
            BufferedImage.TYPE_INT_RGB
        );
        vec2i pixelPos = new vec2i();
        vec3 pixel;
        Graphics2D g = img.createGraphics();
        for (int j = aImage.mSize.y - 1; j >= 0; j--)
        {
            for (int i = 0; i < aImage.mSize.x; i++)
            {
                pixelPos.set(i, j);
                pixel = aImage.read(pixelPos);
                g.setColor(new Color(
                    (float) pixel.x, 
                    (float) pixel.y, 
                    (float) pixel.z
                ));
                g.drawLine(i, j, i, j);
            }
        }
        g.dispose();
        File file = new File(aFullPath);
        try
        {
            file.createNewFile();
            ImageIO.write(img, "png", file);
        }
        catch (Exception e)
        {
            System.err.println("Failed to write image to disk!");
        }
    }
    
}
